package com.jgp.controller;

import com.jgp.common.R;
import lombok.Generated;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basepath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
//       文件原来的名字
        String originalFilename = file.getOriginalFilename();
//        使用uuid重新生成文件名，防止文件覆盖,截取文件格式
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString()+substring;
        log.info(file.toString());
//       创建一个目录对象
        File dir=new File(basepath);
//        如果文件不存在则创建一个
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basepath + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
//        输入流，读取文件内容
        FileInputStream fileInputStream = new FileInputStream(new File(basepath+name));
//        输出流，写回浏览器，进行展示
        ServletOutputStream outputStream = response.getOutputStream();
//图片
        response.setContentType("image/jpeg");
        int len=0;
        byte[]bytes=new byte[1024];
        while ((len=fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        outputStream.close();
        fileInputStream.close();


    }

}
